package com.mrx.giteewebhook.utils;

import lombok.SneakyThrows;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author Mr.X
 * @since 2024-03-08 15:42
 **/
public class GiteeSignUtil {

    /**
     * 计算 gitee webhook 签名工具
     *
     * @param secret    密钥
     * @param timestamp 时间戳 (请求时会带上的)
     * @return 计算后的签名
     */
    @SneakyThrows
    public static String calcSignature(String secret, Long timestamp) {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        // 沙皮 gitee 文档, 不需要做 urlEncode
        return Base64.getEncoder().encodeToString(signData);
    }

}
